﻿using System;
using System.Collections.Generic;
using System.Web;
using TallComponents.Web.Pdf;
using TallComponents.Web.Storage;
using System.IO;

namespace TallComponents.Demo
{
   /// <summary>
   /// A custom PdfStorageProvider that demonstrates how to control access
   /// to pages.
   /// </summary>
   public class LimitedAccessStorageProvider : FileSystemStorageProvider
   {
      /// <summary>
      /// Gets the page.
      /// </summary>
      /// <param name="key">The unique key for the document.</param>
      /// <param name="pageIndex">Index of the page.</param>
      /// <returns>The requested page or <c>null</c>.</returns>
      public override TallComponents.Web.Pdf.Page GetPage( string key, int pageIndex )
      {
         // This implementation only provide access to odd pages
         if ( ( pageIndex % 2 ) == 1 )
         {
            // even page, show the substitute page
            return GetCustomPage();

            // Note that if you return null here the page will be rendered as a transparent image
            // and the thumbnail will remain blank.
         }
         else
         {
            // Odd page, show the page
            return base.GetPage( key, pageIndex );
         }
      }

      private TallComponents.Web.Pdf.Page GetCustomPage()
      {
         try
         {
            // Open not-accessible.pdf and return the first page
            Document doc = new Document( 
                  new FileStream( System.Web.Hosting.HostingEnvironment.MapPath( "~/not-accessible.pdf" ), 
                     FileMode.Open, 
                     FileAccess.Read ), "not-accessible.pdf", "" );

            return doc.Pages[ 0 ];
         }
         catch ( Exception )
         {
            // You could implement error handling here. 
            // Returning null will cause the page to be rendered as a transparent image.
            return null;
         }
      }
   }
}